package com.atguigu.juc.volatiledemo;

import java.util.concurrent.TimeUnit;

/**
 * @Description: volatile 保证变量的可见性
 * @author： yeswater
 * @create： 2024/5/30
 */

public class VolatileSeeDemo {
	
	//static Boolean flag = true;
	static volatile boolean flag = true;
	
	public static void main(String[] args) {
		new Thread(() -> {
			System.out.println(Thread.currentThread().getName() + " start");
			while (flag) {}
			System.out.println(Thread.currentThread().getName() +  " 感知到flag被设置为 false, 程序停止");
		}, "t1").start();
		
		try {
			TimeUnit.SECONDS.sleep(1);
		} catch (InterruptedException e) {
			throw new RuntimeException(e);
		}
		
		flag = false;
		//synchronized (flag) {
		//	flag = false;
		//}
		System.out.println(Thread.currentThread().getName() + " 修改 flag => false");
	}
	
}
